<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/27
 * Time: 11:27
 */

namespace tools;
/**
 * 客户端
 * Class Client
 */
class  Client
{
    private static $sign = [];

    public $server;
    private $callback;
    private $callNum = 0;

    public function __construct($server)
    {
        $this->server = $server;
    }

    /**
     * 取得签名
     * @param array $params
     * @return string
     */
    protected function getSign($params = [])
    {
        ksort($params);
        $param_str = '';

        foreach ($params as $k => $v) {
            if (empty($v)) continue;
            $param_str .= $k . '=' . $v . '&';
        }
        $param_str = rtrim($param_str, '&');

        return md5($param_str . self::$sign[mt_rand(0, count(self::$sign) - 1)]);
    }

    /**
     * 调用服务端接口
     * @param $api
     * @param array $params
     * @param null $callBack
     * @param bool $openSign
     */
    public function call($api, $params = [], $callBack = null, $openSign = true)
    {
        if ($openSign) {
            $params['sign'] = $this->getSign($params);
        }

        if ($callBack === null) {
            $client = new \Yar_Client($this->server);
            return $client->$api($params);
        }
        $this->callNum = $this->callNum + 1;
        $this->callback = $callBack;
        return \Yar_Concurrent_Client::call($this->server, $api, $params, [$this, 'ClientCallBack']);
    }

    /**
     * 执行并发调用
     * @return mixed
     */
    public function loop()
    {
        return \Yar_Concurrent_Client::loop();
    }

    //注册魔术方法


}
